﻿$(document).ready(function () {

    $(".star").mouseover(function () {
        var span = $(this).parent("span");
        var newRating = $(this).attr("value");
        setRating(span, newRating);
    });

    $(".star").mouseout(function () {
        var span = $(this).parent("span");
        var rating = span.attr("rating");
        setRating(span, rating);
    });

    function setRating(span, rating) {
        span.find('img').each(function () {
            var value = parseFloat($(this).attr("value"));
            var imgSrc = $(this).attr("src");
            if (value <= rating)
                $(this).attr("src", imgSrc.replace("-off.png", "-on.png"));
            else
                $(this).attr("src", imgSrc.replace("-on.png", "-off.png"));
        });
    }


    $(".star").click(function () {
            var span = $(this).parent("span");
            var newRating = $(this).attr("value");
            var codeSnippetId = span.attr("codeSnippetId");
            var text = span.children("span");
            $.post("/CodeSnippet/SetRating", { codeSnippetId: codeSnippetId, rating: newRating },
            function (obj) {
                if (obj.Success) {
                    text.html("Currently rated " + obj.Result.Rating + " by " + 
                        obj.Result.TotalRaters + " user(s)"); //modify the text
                    span.attr("rating", obj.Result.Rating); //set the rating attribute
                    setRating(span, obj.Result.Rating); //update the display
                    //alert("Thank you, your vote was casted successfully.");

                    showOkDialog("Thank you. Your vote was cast successfully.", 180, "Voting Accepted", null);
                }
                else {
                    showOkDialog(obj.Message, 180, "Error", null); //failure, show message
//                    alert(obj.Message); 
                }
            }
        );
    });

});